package com.mvvm.library.base;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

import com.mvvm.library.app.XMvvm;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;


/**
 * @创建时间：2023/2/27
 * @作者：小蔡
 * @功能介绍：
 */
public abstract class BaseActivity<T extends ViewDataBinding, V extends ViewModel> extends AppCompatActivity implements View.OnClickListener {
    protected V viewModel;
    protected T binding;
    protected Context mContext;
    protected LinearLayout rootLayout;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        XMvvm.getInstance().addActivity(this);
        binding = DataBindingUtil.setContentView(this, getLayoutId());
        viewModel = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(getTypeClass());
        initView();
    }


    protected abstract void initView();

    /**
     * 获取布局文件id
     *
     * @return LayoutRes
     */
    protected abstract @LayoutRes
    int getLayoutId();

    public Class<V> getTypeClass() {
        ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
        if (type != null) {
            Type[] actualTypeArguments = type.getActualTypeArguments();
            return (Class<V>) actualTypeArguments[1];
        } else {
            return null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        XMvvm.getInstance().removeActivity(this);
    }
}
